package edu.spsu.weather;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import edu.spsu.R;
import edu.spsu.utils.Util;

public class WeatherListingActivity extends Activity {
	private static String TAG = WeatherListingActivity.class.getName();
	public static final String WEATHER_FEED_URL = "http://www.google.com/ig/api?weather=30060";
	public static final int[] icons = { R.id.imageView1, R.id.imageView2,
			R.id.imageView3, R.id.imageView4 };
	public static final int[] days = { R.id.day1, R.id.day2, R.id.day3,
			R.id.day4 };
	public static final int[] conditions = { R.id.condition1, R.id.condition2,
			R.id.condition3, R.id.condition4 };
	public static final int[] lows = { R.id.lowTemperature1,
			R.id.lowTemperature2, R.id.lowTemperature3, R.id.lowTemperature4 };
	public static final int[] highs = { R.id.highTemperature1,
			R.id.highTemperature2, R.id.highTemperature3, R.id.highTemperature4 };
	private GoogleWeatherHandler gwh = null;
	private boolean dataLoaded;

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weather);		
        loadDataFromGoogleWeather();
		setupView();
    	reportLifeCycle("onCreate");
    }
    
    @Override
    protected void onStart() {

    	reportLifeCycle("onStart");
    	super.onStart();
    }

    @Override
    protected void onRestart() {
    	
    	reportLifeCycle("onRestart");
    	super.onRestart();
    }
    
    @Override
    protected void onResume() {
//    	setupView();
    	reportLifeCycle("onResume");
    	super.onResume();
    }

    @Override
    protected void onPause() {
    	super.onPause();
    	reportLifeCycle("onPause");
    }
    
    @Override
    protected void onStop() {
    	super.onStop();
    	reportLifeCycle("onStop");
    }
   
    /** Called when the activity is finished. */
    @Override
    public void onDestroy() {
        super.onDestroy();

    	reportLifeCycle("onDestroy");
    }
    
    private void reportLifeCycle(Object o) {

        Util.report(this, TAG, o+" completed successfully", false);
	}
    
//    private void reportException(Object o) {
//
//        Util.report(this, TAG, "Exception Thrown: "+o, true);
//
//	}
    
	public void taskBarClick(View v) {
		if(v.getId() != R.id.goToWeatherButton)
			Util.taskBarClick(v);
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		setupView();
//		setContentView(R.layout.weather);
	}

	public void setupView() {
		setContentView(R.layout.weather);
		WeatherData weatherData = gwh.getWeatherData();
		try {
			updateCurrentWeatherInfo(weatherData.getCurrentWeatherForecast());
			updateWeatherInfoView("R.id.forecast", weatherData
					.getFutureWeatherForecasts().get(0), 1);
			updateWeatherInfoView("R.id.forecast", weatherData
					.getFutureWeatherForecasts().get(1), 2);
			updateWeatherInfoView("R.id.forecast", weatherData
					.getFutureWeatherForecasts().get(2), 3);
			updateWeatherInfoView("R.id.forecast", weatherData
					.getFutureWeatherForecasts().get(3), 4);
			dataLoaded = true;
			Log.d(TAG, "dataLoaded at end of config change=" + dataLoaded);
		} catch (Exception e) {
			Log.e(TAG, "Error:" + e);
		}
		
	}
		
	public void loadDataFromGoogleWeather() {
		SAXParserFactory spf = SAXParserFactory.newInstance();
		XMLReader xr = null;
		try {
			Log.d(TAG, "Loading Data!");
			SAXParser sp = spf.newSAXParser();
			xr = sp.getXMLReader();
		} catch (Exception e) {
			Log.e(TAG, "Parsing Error:" + e);
		}
		gwh = new GoogleWeatherHandler();
		xr.setContentHandler(gwh);
		URL url = null;
		try {
			url = new URL(WEATHER_FEED_URL);
			xr.parse(new InputSource(url.openStream()));
		} catch (Exception e) {
			Log.d(TAG, "Error:" + e);
		}
	}
	
	// Updates a future weather forecast (1 of the 4)
	private void updateWeatherInfoView(String resource,
			FutureWeatherForecast futureWeatherForecast, int num)
			throws MalformedURLException {
		URL imgUrl = new URL("http://google.com"
				+ futureWeatherForecast.getIcon());
		try {
			URLConnection conn = imgUrl.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is, 2048);
			Bitmap bm = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
			((ImageView) findViewById(icons[num - 1])).setImageBitmap(null);
			((ImageView) findViewById(icons[num - 1])).setImageBitmap(bm);
			((TextView) findViewById(days[num - 1]))
					.setText(futureWeatherForecast.getDay());
			((TextView) findViewById(conditions[num - 1]))
					.setText(futureWeatherForecast.getCondition());
			((TextView) findViewById(highs[num - 1]))
					.setText(futureWeatherForecast.getHighTemperature());
			((TextView) findViewById(lows[num - 1]))
					.setText(futureWeatherForecast.getLowTemperature());
		} catch (IOException e) {
			Log.e(TAG, "Error=" + e);
		}
	}

	// Updates the current weather
	private void updateCurrentWeatherInfo(
			CurrentWeatherForecast currentWeatherForecast)
			throws MalformedURLException {
		URL imgURL = new URL("http://google.com"
				+ currentWeatherForecast.getIcon());
		try {
			URLConnection conn = imgURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is, 2048);
			Bitmap bm = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
			((ImageView) findViewById(R.id.imageView)).setImageBitmap(null);
			((ImageView) findViewById(R.id.imageView)).setImageBitmap(bm);
			((TextView) findViewById(R.id.wind)).setText(currentWeatherForecast
					.getWind());
			((TextView) findViewById(R.id.humidity))
					.setText(currentWeatherForecast.getHumidity());
			((TextView) findViewById(R.id.currentTemperature))
					.setText(currentWeatherForecast.getTemperature());
			((TextView) findViewById(R.id.condition))
					.setText(currentWeatherForecast.getCondition());
		} catch (IOException e) {
			Log.e(TAG, "Error=" + e);
		}
	}
}